function SelectAll(chkAll) {
	var items = $('.shop');
	for (i = 0; i < items.length; i++) {
		if (items[i].id.indexOf("tid") != -1 && items[i].type == "checkbox") {
			items[i].checked = chkAll.checked;
		}
	}
}
function content(msg = ''){
    if(msg == ''){
        $("#content").empty();
    }else{
        $("#content").html('<div class="alert alert-success">'+msg+'</div>');
    }
}
function progress(num = '', msg = ''){
    if(num != ''){
        $("#progress_bar").css('width',num+'%');
        $("#progress_text").text(num+'%');
    }
    $("#progress_msg").html(msg);
}
function next_page(page = 1) {
    var kw = $("#kw").val();
	var cid = $("#cid").val();
	var range = $("#range").val();
	var status = $("#status").val();
	var shequ = $("input[name='shequ']").val();
	if(cid==-2)return;
	var ii = layer.load(2, {shade:[0.1,'#fff']});
	shoplist = new Array();
	
    $.ajax({
		type : "POST",
		url : "ajax_sf.php?act=allgoodslist",
		dataType : 'json',
		data : {shequ:shequ, cid:cid, num:30, page:page, kw:kw, range:range, status:status},
		success : function(data) {
			layer.close(ii);
			if(data.code == 0){
				var num = 0;
				var html = '<div class="table-responsive"><table class="table table-striped"><thead><tr><td><label class="csscheckbox csscheckbox-primary"><input type="checkbox" onclick="SelectAll(this)"><span></span></label>&nbsp;ID</td><td>商品名称</td><td>分类名称</td><td>成本价</td><td>上架状态</td><td>对接状态</td><td>上架时间</td><td>操作</td></tr></thead><tbody>';
				$.each(data.data, function (i, item) {
					shoplist[item.tid] = JSON.stringify(item);
					html += '<tr><td><label class="csscheckbox csscheckbox-primary"><input name="tid[]" type="checkbox" class="shop" id="tid" value="'+item.tid+'"><span></span>&nbsp;'+item.tid+'<label></label></label></td><td>'+item.name+'</td><td>对接分类名：'+(item.classname == null?'未分类':item.classname)+''+(item.status==1?'<br>本站分类名：'+item.localclassname:'')+'</td><td>'+item.price+'</td><td>'+(item.close==1?'<span class="btn btn-xs btn-warning">已下架</span>':'<span class="btn btn-xs btn-success">上架中</span>')+'</td><td>'+(item.status==1?'<span class="btn btn-xs btn-success">已对接</span>':'<span class="btn btn-xs btn-warning">未对接</span>')+'</td><td>'+item.addtime+'</td><td>'+(item.status==1?'<a onclick="add('+item.tid+',\''+item.name+'\')" class="btn btn-xs btn-primary">更新</a> <a target="_blank" href="./shopedit.php?my=edit&tid='+item.localtid+'" class="btn btn-xs btn-info">编辑</a>':'<a onclick="add('+item.tid+',\''+item.name+'\')" class="btn btn-xs btn-danger">对接</a>')+'</td></tr>';
					num++;
				});
				if(num==0){
				    content('');
				    layer.msg('未查询到符合条件的商品', {icon:0, time:800});
				    return false;
				}
				html += '</tbody></table></div><ul class="pagination">';
				if(page > 1){
				    html += '<li onclick="next_page(1)"><a>首页</a></li>';
				}else{
				    html += '<li class="disabled"><a>首页</a></li>';
				}
				var start = (page - 10 > 1) ? page - 10 : 1;
                var end = ((page + 10) < data.page) ? page + 10 : data.page;
				for (var i = start; i < page; i++) {
				    html += '<li><a href="javascript:void(0)" onclick="next_page('+i+')">'+i+'</a></li>';
				}
				html += '<li class="disabled"><a>'+page+'</a></li>';
				for (var i = (page + 1); i <= end; i++) {
				    html += '<li><a href="javascript:void(0)" onclick="next_page('+i+')">'+i+'</a></li>';
				}
				if(page < data.page){
				    html += '<li><a href="javascript:void(0)" onclick="next_page('+data.page+')">尾页</a></li></ul>';
				}else{
				    html += '<li class="disabled"><a>尾页</a></li></ul>';
				}
				if(kw == ''){
				    if(cid == '0'){
				        content('全部商品共'+data.count+'个');
				    }else{
				        content('当前分类商品共'+data.count+'个');
				    }
				}else{
				    if(cid == '0'){
				        content('关于【'+kw+'】的商品共'+data.count+'个');
				    }else{
				        content('关于【'+kw+'】的商品当前分类共'+data.count+'个');
				    }
				}
				$("#shoplist").html(html);
			}else{
				layer.alert(data.msg, {icon:2});
			}
		},
		error:function(data){
			layer.msg('加载失败，请刷新重试');
			return false;
		}
	});
}
var shoplist;
var add_success = 0;
var update_success = 0;
var page = 1;
var total = 0;
var count = 0;
var is_bool = false;
function add(tid = '',name = ''){
    layer.open({
        title: '对接'+name,
        content: $("#addhtml").html(),
        btn:['确认对接'],
        success: function(index, layero){
        	if(tid == ''){
        		layer.alert('参数错误，请刷新页面重试~');
        		return false;
        	}
        },
        yes: function(index, layero){
            var shequ = $("input[name='shequ']").val();
        	var mcid = $("#mcid").val();
        	var prid = $("#prid").val();
        	if(mcid == -1){
        		layer.alert('请选择保存到本站的分类');return false;
        	}
        	if(prid == -1){
        		layer.alert('请选择使用的加价模板');return false;
        	}
        	var newshoplist = new Array();
        	newshoplist.push(shoplist[tid]);
        	var ii = layer.load(2, {shade:[0.1,'#fff']});
        	$.ajax({
        		type : "POST",
        		url : "ajax_sf.php?act=batchaddgoods",
        		dataType : 'json',
        		data : {shequ:shequ, mcid:mcid, prid:prid, list:newshoplist, cname:$("#cid option:selected").text(), cimg:$("#cid option:selected").attr('data-shopimg')},
        		success : function(data) {
        			layer.close(ii);
        			if(data.code == 0){
        				layer.alert(data.msg, {icon:1}, function(){window.location.reload()});
        			}else{
        				layer.alert(data.msg, {icon:2});
        			}
        		},
        		error:function(data){
        			layer.msg('加载失败，请刷新重试');
        			return false;
        		}
        	});
            layer.close(index);
        }
    });
}
function all_batchaddgoods(page,shequ,mcid,prid){
    if(!is_bool){
        layer.closeAll();
        layer.msg('已成功停止对接！<br>总进度:'+total+'/'+count+'<br>成功添加'+add_success+'个商品，更新'+update_success+'个商品！',{icon:1});
        add_success = 0;
        update_success = 0;
        page = 1;
        total = 0;
        return false;
    }
	$.ajax({
		type : "POST",
		url : "ajax_sf.php?act=all_batchaddgoods",
		dataType : 'json',
		data : {shequ:shequ, mcid:mcid, prid:prid,page:page,total:total},
		success : function(data) {
			add_success += data.add;
			update_success += data.update;
			total += data.add + data.update;
			count = data.count;
			progress(data.percent,'总进度:'+total+'/'+count+'<br>成功添加'+add_success+'个商品，更新'+update_success+'个商品！');
			if(data.code == 1){
			    add_success = 0;
                update_success = 0;
                page = 1;
                total = 0;
				layer.alert('对接全部商品成功！', {icon:1}, function(){
				    window.location.reload()
				});
			}else if(data.code == 0){
				all_batchaddgoods(++page,shequ,mcid,prid);
			}else{
				layer.alert(data.msg, {icon:2});
			}
		},
		error:function(data){
			layer.msg('加载失败，请刷新重试');
			return false;
		}
	});
}
$(document).ready(function(){
    $("#add_submit").click(function () {
        var newshoplist = new Array();
        layer.open({
            title: '批量对接',
            content: $("#addhtml").html(),
            btn:['确认对接'],
            success: function(index, layero){
            	var items = $('.shop');
            	for (i = 0; i < items.length; i++) {
            		if (items[i].id.indexOf("tid") != -1 && items[i].type == "checkbox" && items[i].checked == true) {
            			var tid = items[i].value;
            			newshoplist.push(shoplist[tid]);
            		}
            	}
            	if(newshoplist.length <= 0){
            		layer.alert('请至少选中一个商品');return false;
            	}
            },
            yes: function(index, layero){
                var shequ = $("input[name='shequ']").val();
            	var mcid = $("#mcid").val();
            	var prid = $("#prid").val();
            	if(mcid == -1){
            		layer.alert('请选择保存到本站的分类');return false;
            	}
            	if(prid == -1){
            		layer.alert('请选择使用的加价模板');return false;
            	}
            	var ii = layer.load(2, {shade:[0.1,'#fff']});
            	$.ajax({
            		type : "POST",
            		url : "ajax_sf.php?act=batchaddgoods",
            		dataType : 'json',
            		data : {shequ:shequ, mcid:mcid, prid:prid, list:newshoplist},
            		success : function(data) {
            			layer.close(ii);
            			if(data.code == 0){
            				layer.alert(data.msg, {icon:1}, function(){window.location.reload()});
            			}else{
            				layer.alert(data.msg, {icon:2});
            			}
            		},
            		error:function(data){
            			layer.msg('加载失败，请刷新重试');
            			return false;
            		}
            	});
                layer.close(index);
            }
        });
    	
    });
    $("#all_submit").click(function () {
        layer.open({
            title: '全部对接',
            content: $("#addhtml").html(),
            btn:['确认对接'],
            yes: function(index, layero){
                var shequ = $("input[name='shequ']").val();
            	var mcid = $("#mcid").val();
            	var prid = $("#prid").val();
            	if(mcid == -1){
            		layer.alert('请选择保存到本站的分类');return false;
            	}
            	if(prid == -1){
            		layer.alert('请选择使用的加价模板');return false;
            	}
            	layer.confirm('是否确认对接全部商品?<br><div style="color:red">此过程可能时间过长，期间请勿关闭该窗口</div>', {icon: 3, title:'提示'}, function(index){
                	var ii = layer.load(2, {shade:[0.1,'#fff']});
                	$.ajax({
                		type : "POST",
                		url : "ajax_sf.php?act=all_batchaddgoods",
                		dataType : 'json',
                		data : {shequ:shequ, mcid:mcid, prid:prid},
                		success : function(data) {
                			layer.close(ii);
                			add_success += data.add;
                			update_success += data.update;
                			total += data.add + data.update;
                			if(data.code == 1){
                			    add_success = 0;
                                update_success = 0;
                                page = 1;
                                total = 0;
                				layer.alert('对接全部商品成功！', {icon:1}, function(){
                				    window.location.reload()
                				});
                			}else if(data.code == 0){
                			    is_bool = true;
                			    layer.open({
                                    title: '全部对接进度',
                                    content: $("#allhtml").html(),
                                    area: '400px',
                                    btn:['停止对接'],
                                    closeBtn:false,
                                    success: function(index, layero){
                                        progress(data.percent,'总进度:'+total+'/'+data.count+'<br>成功添加'+add_success+'个商品，更新'+update_success+'个商品！');
                                    },
                                    yes: function(index, layero){
                                        progress('','总进度:'+total+'/'+data.count+'<br>正在停止对接...');
                                        is_bool = false;
                                    }
                				});
                				all_batchaddgoods(++page,shequ,mcid,prid);
                			}else{
                				layer.alert(data.msg, {icon:2});
                			}
                		},
                		error:function(data){
                			layer.msg('加载失败，请刷新重试');
                			return false;
                		}
                	});
                    layer.close(index);
            	});
            }
        });
    	
    });
    $("#search").click(function () {
    	var cid = $("#cid").val();
    	var kw = $("#kw").val();
    	var range = $("#range").val();
        var status = $("#status").val();
    	var shequ = $("input[name='shequ']").val();
    	if(cid==-2){
    	    layer.msg('请先选择分类');
			return false;
    	}
    	var ii = layer.load(2, {shade:[0.1,'#fff']});
    	shoplist = new Array();
    	$("#shoplist").empty();
    	content('');
        $.ajax({
    		type : "POST",
    		url : "ajax_sf.php?act=allgoodslist",
    		dataType : 'json',
    		data : {shequ:shequ, cid:cid, num:30, page:1, kw:kw, range:range, status:status},
    		success : function(data) {
    			layer.close(ii);
    			if(data.code == 0){
    				var num = 0;
    				var html = '<div class="table-responsive"><table class="table table-striped"><thead><tr><td><label class="csscheckbox csscheckbox-primary"><input type="checkbox" onclick="SelectAll(this)"><span></span></label>&nbsp;ID</td><td>商品名称</td><td>分类名称</td><td>成本价</td><td>上架状态</td><td>对接状态</td><td>上架时间</td><td>操作</td></tr></thead><tbody>';
    				$.each(data.data, function (i, item) {
    					shoplist[item.tid] = JSON.stringify(item);
    					html += '<tr><td><label class="csscheckbox csscheckbox-primary"><input name="tid[]" type="checkbox" class="shop" id="tid" value="'+item.tid+'"><span></span>&nbsp;'+item.tid+'<label></label></label></td><td>'+item.name+'</td><td>对接分类名：'+(item.classname == null?'未分类':item.classname)+''+(item.status==1?'<br>本站分类名：'+item.localclassname:'')+'</td><td>'+item.price+'</td><td>'+(item.close==1?'<span class="btn btn-xs btn-warning">已下架</span>':'<span class="btn btn-xs btn-success">上架中</span>')+'</td><td>'+(item.status==1?'<span class="btn btn-xs btn-success">已对接</span>':'<span class="btn btn-xs btn-warning">未对接</span>')+'</td><td>'+item.addtime+'</td><td>'+(item.status==1?'<a onclick="add('+item.tid+',\''+item.name+'\')" class="btn btn-xs btn-primary">更新</a> <a target="_blank" href="./shopedit.php?my=edit&tid='+item.localtid+'" class="btn btn-xs btn-info">编辑</a>':'<a onclick="add('+item.tid+',\''+item.name+'\')" class="btn btn-xs btn-danger">对接</a>')+'</td></tr>';
    					num++;
    				});
    				if(num==0){
    				    content();
    				    layer.msg('未搜索到相关商品', {icon:0, time:800});
    				    return false;
    				}
    				html += '</tbody></table></div><ul class="pagination "><li class="disabled"><a>首页</a></li><li class="disabled"><a>1</a></li>';
    				var page = (data.page > 10)?10:data.page;
    				for (var i = 2; i <= page; i++) {
    				    html += '<li><a href="javascript:void(0)" onclick="next_page('+i+')">'+i+'</a></li>';
    				}
    				html += '<li><a href="javascript:void(0)" onclick="next_page('+data.page+')">尾页</a></li></ul>';
    				if(cid == '0'){
				        content('关于【'+kw+'】的商品共'+data.count+'个');
				    }else{
				        content('关于【'+kw+'】的商品当前分类共'+data.count+'个');
				    }
    				$("#shoplist").html(html);
    			}else{
    				layer.alert(data.msg, {icon:2});
    			}
    		},
    		error:function(data){
    		    content();
    			layer.msg('加载失败，请刷新重试');
    			return false;
    		}
    	});
    });
    $("#cid").focus(function () {
        console.log($(this).val());
        $("#cid").val('-2');
    }).change(function () {
        var kw = $("#kw").val();
    	var cid = $("#cid").val();
    	var range = $("#range").val();
	    var status = $("#status").val();
    	var shequ = $("input[name='shequ']").val();
    	if(cid==-2)return;
    	var ii = layer.load(2, {shade:[0.1,'#fff']});
    	shoplist = new Array();
    	$("#shoplist").empty();
    	content('');
    	$('#cid').blur();
        $.ajax({
    		type : "POST",
    		url : "ajax_sf.php?act=allgoodslist",
    		dataType : 'json',
    		data : {shequ:shequ, cid:cid, num:30, page:1, range:range, kw:kw, status:status},
    		success : function(data) {
    			layer.close(ii);
    			if(data.code == 0){
    				var num = 0;
    				var html = '<div class="table-responsive"><table class="table table-striped"><thead><tr><td><label class="csscheckbox csscheckbox-primary"><input type="checkbox" onclick="SelectAll(this)"><span></span></label>&nbsp;ID</td><td>商品名称</td><td>分类名称</td><td>成本价</td><td>上架状态</td><td>对接状态</td><td>上架时间</td><td>操作</td></tr></thead><tbody>';
    				$.each(data.data, function (i, item) {
    					shoplist[item.tid] = JSON.stringify(item);
    					html += '<tr><td><label class="csscheckbox csscheckbox-primary"><input name="tid[]" type="checkbox" class="shop" id="tid" value="'+item.tid+'"><span></span>&nbsp;'+item.tid+'<label></label></label></td><td>'+item.name+'</td><td>对接分类名：'+(item.classname == null?'未分类':item.classname)+''+(item.status==1?'<br>本站分类名：'+item.localclassname:'')+'</td><td>'+item.price+'</td><td>'+(item.close==1?'<span class="btn btn-xs btn-warning">已下架</span>':'<span class="btn btn-xs btn-success">上架中</span>')+'</td><td>'+(item.status==1?'<span class="btn btn-xs btn-success">已对接</span>':'<span class="btn btn-xs btn-warning">未对接</span>')+'</td><td>'+item.addtime+'</td><td>'+(item.status==1?'<a onclick="add('+item.tid+',\''+item.name+'\')" class="btn btn-xs btn-primary">更新</a> <a target="_blank" href="./shopedit.php?my=edit&tid='+item.localtid+'" class="btn btn-xs btn-info">编辑</a>':'<a onclick="add('+item.tid+',\''+item.name+'\')" class="btn btn-xs btn-danger">对接</a>')+'</td></tr>';
    					num++;
    				});
    				if(num==0){
    				    content('');
    				    layer.msg('未查询到符合条件的商品', {icon:0, time:800});
    				    return false;
    				}
    				html += '</tbody></table></div><ul class="pagination" style="text-aligin:center"><li class="disabled"><a>首页</a></li><li class="disabled"><a>1</a></li>';
    				var page = (data.page > 10)?10:data.page;
    				for (var i = 2; i <= page; i++) {
    				    html += '<li><a href="javascript:void(0)" onclick="next_page('+i+')">'+i+'</a></li>';
    				}
    				html += '<li><a href="javascript:void(0)" onclick="next_page('+data.page+')">尾页</a></li></ul>';
    				if(cid == '0'){
				        content('全部商品共'+data.count+'个');
				    }else{
				        content('当前分类商品共'+data.count+'个');
				    }
    				$("#shoplist").html(html);
    			}else{
    				layer.alert(data.msg, {icon:2});
    			}
    		},
    		error:function(data){
    		    content();
    			layer.msg('加载失败，请刷新重试');
    			return false;
    		}
    	});
    });
})